<template>
  <div>
    <el-card>
      <el-form ref="albumFormRef" :model="albumForm" :rules="albumFormRules" label-width="90px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="albumForm.title" placeholder="请输入相册标题"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="pubDate">
          <el-col :span="11">
            <el-date-picker type="month" placeholder="选择日期" v-model="albumForm.pubDate" format="yyyy 年 MM 月" style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="上传照片" prop="pictures">
          <div style="width: 500px;">
            <el-upload
              ref="uploadRef"
              :limit="16"
              :action="baseURI+'picture/upload'"
              :file-list="fileList"
              :data="albumForm"
              :on-change="uploadChanged"
              :before-remove="uploadRemoved"
              :on-exceed="uploadExceed"
              :before-upload="beforeFileUpload"
              :multiple="true"
              :on-success="uploadSucceed"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过5Mb</div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button v-if="isAdd" type="primary" @click="submitAlbum" :disabled="uploadingCount > 0">立即创建</el-button>
          <el-button v-else type="primary" @click="submitAlbum" :disabled="uploadingCount > 0">立即更新</el-button>
          <el-button v-if="isAdd" type="info" @click="resetAlbum">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  props: {
    isAdd: {
      type: Boolean,
      default: true
    }
  },
  computed: {
    activeTab () {
      return this.$store.state.activeTab
    }
  },
  watch: {
    activeTab: function (val, oldval) {
      if (this.isAdd) return
      if (val === 'updateAlbum') {
        if (!this.$store.state.activeAlbum) {
          this.$store.commit('setActiveTab', 'viewAlbum')
          this.$notify({ title: '注意', message: '请先选择要更新的相册', type: 'warning' })
          return
        }
        var form = this.$store.state.activeAlbum
        form = JSON.parse(JSON.stringify(form))
        form.pubDate = new Date(form.pubDate)
        delete form.addTime
        this.albumForm = form
        this.albumForm.pictures.forEach(item => {
          this.fileList = this.fileList.concat({ name: item.filename, url: this.baseURI + 'upload/' + item.thumbnails_uploadId, picture: item })
        })
      } else {
        this.resetAlbum()
        this.$store.commit('setActiveAlbum', null)
      }
    }
  },
  data () {
    return {
      uploadingCount: 0,
      baseURI: null,
      fileList: [],
      uploadParam: {
        token: null
      },
      albumForm: {
        token: null,
        title: null,
        pubDate: null,
        pictures: []
      },
      albumFormRules: {
        title: [
          { required: false, message: '请输入相册标题', trigger: 'blur' }
        ],
        pubDate: [
          { required: false, message: '请选择活动时间', trigger: 'blur' }
        ],
        pictures: [
          { required: true, message: '请上传照片', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.baseURI = this.$http.defaults.baseURL
  },
  methods: {
    submitAlbum () {
      this.albumForm.token = window.sessionStorage.getItem('token')
      var pictures = []
      this.fileList.forEach(file => {
        pictures = pictures.concat(file.picture)
      })
      this.albumForm.pictures = pictures
      this.$refs.albumFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('album/submit', this.albumForm)
        if (!res.success) {
          this.$message.error(res.info)
        } else {
          this.$message.success(res.info)
          this.$store.commit('setAlbumListBlur', true)
          if (this.isAdd) this.resetAlbum()
          else this.$store.commit('setActiveTab', 'viewAlbum')
        }
      })
    },
    resetAlbum () {
      this.uploadingCount = 0
      this.$refs.albumFormRef.resetFields()
      this.$refs.uploadRef.abort()
      this.$refs.uploadRef.clearFiles()
      this.fileList = []
      this.message = '准备上传'
    },
    uploadChanged (file, fileList) {
      this.fileList = fileList
    },
    uploadExceed (file, fileList) {
      this.$message.error('最多只能上传 16 个文件')
    },
    uploadRemoved (file, fileList) {
      this.uploadChanged(file, fileList)
      if (file.status === 'uploading') this.uploadingCount--
    },
    uploadSucceed (res, file, fileList) {
      this.uploadingCount--
      if (!res.success) {
        this.$message.error(res.info)
      }
      file.picture = res.picture
      console.log(this.fileList)
    },
    beforeFileUpload (file) {
      const isJpg = file.type === 'image/jpeg'
      const isPng = file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isJpg && !isPng) this.$message.error('上传文件只能是 JPG/PNG 格式!')
      else if (!isLt5M) this.$message.error('上传文件大小不能超过 5MB!')
      this.albumForm.token = window.sessionStorage.getItem('token')
      if ((isPng || isJpg) && isLt5M) this.uploadingCount++
      return (isPng || isJpg) && isLt5M
    }
  }
}
</script>

<style scoped>
</style>
